package com.edevp.common.security.interceptor;


import com.edevp.common.core.exception.EngineException;
import com.edevp.common.core.util.CommonUtil;
import com.edevp.common.security.dto.AuthTokenDTO;
import com.edevp.common.security.exception.AuthExceptionCode;
import com.edevp.common.security.util.TokenUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Nonnull;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 校验token
 * @author Blueeyedboy
 * @create 2022-07-08 6:39 PM
 **/
public class AuthInterceptor  implements HandlerInterceptor {
	@Override
	public boolean preHandle(@Nonnull HttpServletRequest request, @Nonnull HttpServletResponse response, @Nonnull Object handler)  {
		// 获取token
		String token = TokenUtil.getToken(request);
		if(CommonUtil.isNull(token)){
			throw new EngineException(AuthExceptionCode.AUTH_TOKEN_REQUIRED);
		}
		// 解析token
		AuthTokenDTO tokenDTO = TokenUtil.getToken(token);
		if(tokenDTO == null){
			throw new EngineException(AuthExceptionCode.AUTH_TOKEN_NOT_FIND);
		}
		if(!tokenDTO.getToken().equals(token)){
			throw new EngineException(AuthExceptionCode.AUTH_TOKEN_INCORRECT);
		}
		return true;
	}
}